"""
@author: ertao.xyz
@create: 2021-12-15 18:17
@description: 
"""
from typing import List, Optional, Any
from tortoise.transactions import atomic
from fastapi import APIRouter, Depends, status, HTTPException, Request, Body, Path
from utils.response_code import ResultResponse, HttpStatus
from auth.auth_casbin import Authority
from utils import crud as curd
from utils import crud

from . import model, schema

router = APIRouter()


@router.post("/getWxminiList",
             summary="获取微信小程序列表",
             response_model=ResultResponse[str]
             )
async def getWxminiList(request: Request, ):
    # if settings.REDIS:
    #     # r.hset("Token", "k1", "v1")
    #     r.hdel("Token", request.state.user.pk)
    return ResultResponse(message='退出成功')


@router.get('/wxmini/',
            summary='获取微信小程序列表',
            name='获取微信小程序列表',
            response_model=ResultResponse[List[schema.WxMiniOut]],
            dependencies=[Depends(Authority('wechatmini,read'))])
async def get_wxmini_list(page: int = 1, pageSize: int = 20, name: Optional[str] = None):
    query = model.WechatMini.all()
    if name is not None:
        query = query.filter(name__icontains=name)
    query = await query.offset(page - 1).limit(pageSize)
    # user_list = await crud.get_user_list()
    return ResultResponse[List[schema.WxMiniOut]](result=query)


@router.post('/wxmini/',
             summary='添加微信小程序',
             name='添加微信小程序',
             response_model=ResultResponse[schema.WxMiniOut],
             dependencies=[Depends(Authority('wechatmini,add'))])
async def add_wxmini(wxmini: schema.WxMiniIn):
    if await crud.has_obj_by_name(model.WechatMini, wxmini.name):
        return ResultResponse[str](code=HttpStatus.HTTP_601_ROLE_EXIST, message='角色已存在')
    obj = await crud.create_obj(wxmini)
    return ResultResponse[schema.WxMiniOut](result=obj)


@router.delete('/wxmini/',
               summary='删除微信小程序',
               name='删除微信小程序',
               response_model=ResultResponse[str],
               dependencies=[Depends(Authority('wechatmini,del'))])
async def del_wxmini(request: Request, ids: List[int]):
    result = await curd.delete_obj_by_ids(model.WechatMini, ids)
    if not result:
        return ResultResponse[str](code=HttpStatus.HTTP_600_ROLE_NOT_EXIST, message='微信小程序不存在')
    return ResultResponse[str](message='删除成功')


@router.put('/wxmini/{id}',
            summary='更新微信小程序',
            name='更新微信小程序',
            response_model=ResultResponse[schema.WxMiniOut],
            dependencies=[Depends(Authority('wechatmini,update'))])
async def update_wxmini(id: int, data: schema.WxMiniIn):
    obj = await curd.update_obj_by_id(model.WechatMini, id, data)
    return ResultResponse[schema.WxMiniOut](result=obj)
